package com.sk.weichat.ui.contacts;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cjt2325.cameralibrary.util.LogUtil;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.HadAddContactsAdapter;
import com.sk.weichat.bean.AddAttentionResult;
import com.sk.weichat.bean.Contacts;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.NewContactsBean;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.FriendHelper;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.message.search.SearchActivity;
import com.sk.weichat.util.AnimationUtil;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.ContactsUtil;
import com.sk.weichat.util.ListUtil;
import com.sk.weichat.util.PermissionUtil;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import okhttp3.Call;

public class NewContactsActivity extends BaseActivity implements PermissionUtil.OnRequestPermissionsResultCallbacks {

    private static final int REQUEST_CONTACTS_CODE = 1022;

    private Map<String, Contacts> phoneContacts;
    private List<BaseSortModel<NewContactsBean>> mSortContactList = new ArrayList<>();
    private List<BaseSortModel<NewContactsBean>> mAddSortContactList = new ArrayList<>();

    private ContactsAdapter contactsAdapter;
    private RecyclerView mListView;

    private LinearLayout ll_contacts_head;
    private RecyclerView recy_had_add;
    private HadAddContactsAdapter hadAddContactsAdapter;//已添加好友适配

    private TextView tvTitleRight, mTextDialog, tvNoContacts, tvConfirm;
    private SideBar mSideBar;

    private LinearLayout linearNoPermission, linearShare;
    private Button btnOpenPermission;

    private boolean isInvitedMod;

    private int lvScrollPosition;
    private LinearLayoutManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_contacts);
        initView();
        boolean isReadContacts = PermissionUtil.checkSelfPermissions(this, new String[]{Manifest.permission.READ_CONTACTS});
        if (!isReadContacts) {
            linearNoPermission.setVisibility(View.VISIBLE);
            showEmpty();
            return;
        }
        linearNoPermission.setVisibility(View.GONE);
        getContacts();
    }

    private void initView() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText(getString(R.string.phone_contact));
        tvTitleRight = findViewById(R.id.tv_title_right);
        tvTitleRight.setTextColor(getResources().getColor(R.color.deep_purple));
        tvTitleRight.setText("批量邀请");
        linearNoPermission = findViewById(R.id.linear_no_permission);
        btnOpenPermission = findViewById(R.id.btn_set_permission);
        btnOpenPermission.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionUtil.startApplicationDetailsSettings(NewContactsActivity.this, REQUEST_CONTACTS_CODE);
//                boolean onceAgain = PermissionUtil.deniedRequestPermissionsAgain(NewContactsActivity.this, new String[]{Manifest.permission.READ_CONTACTS});
//                if (!onceAgain) {
//                    PermissionUtil.requestPermissions(NewContactsActivity.this, 0x01, new String[]{Manifest.permission.READ_CONTACTS});
//                    TipDialog mTipDialog = new TipDialog(mContext);
//                    mTipDialog.setmConfirmOnClickListener("你还未开启读取联系人权限，是否前往手动开启", new TipDialog.ConfirmOnClickListener() {
//                        @Override
//                        public void confirm() {
//                            PermissionUtil.startApplicationDetailsSettings(NewContactsActivity.this, REQUEST_CONTACTS_CODE);
//                        }
//                    });
//                    mTipDialog.show();
//                }
//                else {
//                    PermissionUtil.requestPermissions(NewContactsActivity.this, 0x01, new String[]{Manifest.permission.READ_CONTACTS});
//                }
            }
        });
        tvNoContacts = findViewById(R.id.tv_no_contacts);
        tvConfirm = findViewById(R.id.tv_invite_confirm);
        mSideBar = findViewById(R.id.sidebar);
        mTextDialog = findViewById(R.id.text_dialog);
        mSideBar.setTextView(mTextDialog);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = ListUtil.getSortContactssPositionForSection(mSortContactList, s.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position + 1, 0);
                    showTextDialog(s);
                }
            }
        });
        contactsAdapter = new ContactsAdapter(mSortContactList);
        mListView = findViewById(R.id.pull_refresh_list);
        manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mListView.setLayoutManager(manager);


        //已添加好友列表
        View headView = LayoutInflater.from(this).inflate(R.layout.layout_recy, mListView, false);
        contactsAdapter.addHeaderView(headView);
        ll_contacts_head = headView.findViewById(R.id.ll_contacts_head);
        TextView tite = headView.findViewById(R.id.tv_title);
        tite.setVisibility(View.GONE);
        recy_had_add = headView.findViewById(R.id.recy_had_add);
        hadAddContactsAdapter = new HadAddContactsAdapter(mAddSortContactList);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_had_add.setLayoutManager(manager);
        recy_had_add.setNestedScrollingEnabled(true);
        hadAddContactsAdapter.setHasStableIds(true);
        recy_had_add.setAdapter(hadAddContactsAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recy_had_add.getItemAnimator()).setSupportsChangeAnimations(false);
        hadAddContactsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                NewContactsBean Contacts = mAddSortContactList.get(position).bean;
                Friend friend  =  FriendDao.getInstance().getFriend(coreManager.getSelf().getUserId(), Contacts.getUserId());

                if (view.getId()==R.id.avatar_img){
                    Intent intent = new Intent(NewContactsActivity.this, PersonalCenterActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, Contacts.getUserId());
                    startActivity(intent);
                }else {
                    Intent intent = new Intent(NewContactsActivity.this, ChatActivity.class);
                    intent.putExtra(ChatActivity.FRIEND, friend);
                    intent.putExtra(Constants.NEW_MSG_NUMBER,  friend.getUnReadNum());
                    startActivity(intent);

                }
//                Intent intent = new Intent(NewContactsActivity.this, PersonalCenterActivity.class);
//                intent.putExtra(AppConstant.EXTRA_USER_ID, Contacts.getUserId());
//                startActivity(intent);
            }
        });
        contactsAdapter.setHasStableIds(true);
        mListView.setAdapter(contactsAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) mListView.getItemAnimator()).setSupportsChangeAnimations(false);
        tvTitleRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isControlBatchStatus(true);
            }
        });
        initEvent();
    }

    private void initEvent() {
        TextView shareAppTv = findViewById(R.id.tv_share_app);
        shareAppTv.setText(getString(R.string.share_app, getString(R.string.app_name)));
        linearShare = findViewById(R.id.linear_invited_share);
        findViewById(R.id.linear_invited_share).setOnClickListener(v -> {
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.sms_content, getString(R.string.app_name))
                    + coreManager.getConfig().website);
            shareIntent = Intent.createChooser(shareIntent, getString(R.string.sms_content, getString(R.string.app_name))
                    + coreManager.getConfig().website);
            startActivity(shareIntent);
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSortContactList != null && mSortContactList.size() > 0) {
                    String telStr = "";
                    for (int i = 0; i < mSortContactList.size(); i++) {
                        if (mSortContactList.get(i).getBean().isChecked()) {
                            String tel = mSortContactList.get(i).getBean().getTelephone();
                            telStr += tel + ";";
                        }
                    }
                    if (!TextUtils.isEmpty(telStr)) {
                        sendSms(telStr);
                    } else {
                        ToastUtil.showToast(mContext, "请选择需要邀请的联系人");
                    }
                }
            }
        });
        mListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int visibleItemCount = manager.getChildCount();//屏幕可见item数
                int totalItemCount = manager.getItemCount();//总item数
                int pastVisibleItems = manager.findFirstVisibleItemPosition();//屏幕显示的第一个item的下标index
                if (pastVisibleItems > 1 && visibleItemCount + pastVisibleItems < totalItemCount) {
                    int firstIndex = pastVisibleItems - 1;
                    String firstStr = ListUtil.getFirstContactsStr(mSortContactList, firstIndex);
                    mSideBar.searchByFirstStr(firstStr);
                    String strLast = ListUtil.getFirstContactsStr(mSortContactList, pastVisibleItems - 2);
                    String strSec = ListUtil.getFirstContactsStr(mSortContactList, pastVisibleItems);
                    if (lvScrollPosition < firstIndex) {
                        if (!firstStr.equals(strLast)) {
                            showTextDialog(firstStr);
                        }
                    } else if (lvScrollPosition > firstIndex) {
                        if (!firstStr.equals(strSec)) {
                            showTextDialog(firstStr);
                        }
                    }
                }
                lvScrollPosition = pastVisibleItems - 1;
            }
        });



      /*  mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem + visibleItemCount != totalItemCount) {
                    String firstStr = contactsAdapter.getFirstStr(firstVisibleItem);
                    if (firstStr != null && !firstStr.equals("")) {
                        mSideBar.searchByFirstStr(firstStr);
                        if (firstVisibleItem != 0) {
                            String strLast = contactsAdapter.getFirstStr(firstVisibleItem - 1);
                            String strSec = contactsAdapter.getFirstStr(firstVisibleItem + 1);
                            if (lvScrollPosition < firstVisibleItem) {
                                if (!firstStr.equals(strLast)) {
                                    showTextDialog(firstStr);
                                }
                            } else if (lvScrollPosition > firstVisibleItem) {
                                if (!firstStr.equals(strSec)) {
                                    showTextDialog(firstStr);
                                }
                            }
                        }
                    }
                }
                lvScrollPosition = firstVisibleItem;
            }
        });*/
//        boolean isExistContactGroup = false;
//        List<Friend> mFriendList = FriendDao.getInstance().getAllRooms(coreManager.getSelf().getUserId());
//        for (int i = 0; i < mFriendList.size(); i++) {
//            Friend friend = mFriendList.get(i);
//            if (friend != null && friend.getRoomFlag() == 510) {
//                isExistContactGroup = true;
//                mRoomId = mFriendList.get(i).getRoomId();
//            }
//        }
//
//        if (isExistContactGroup) {// 存在我的联系人群组 , 弹出界面提示是否邀请进群
//            SelectionFrame mSelectionFrame = new SelectionFrame(this);
//            mSelectionFrame.setSomething(null, getString(R.string.is_invite), new SelectionFrame.OnSelectionFrameClickListener() {
//                @Override
//                public void cancelClick() {
//
//                }
//
//                @Override
//                public void confirmClick() {
//                    go(mRoomId, false);
//                }
//            });
//            mSelectionFrame.show();
//        } else if (!coreManager.getLimit().cannotCreateGroup()) {// 不存在 ' 我的手机联系人' 群组 提示建群
//            SelectionFrame mSelectionFrame = new SelectionFrame(this);
//            mSelectionFrame.setSomething(null, getString(R.string.is_create), new SelectionFrame.OnSelectionFrameClickListener() {
//                @Override
//                public void cancelClick() {
//
//                }
//
//                @Override
//                public void confirmClick() {
//                    showCreateGroupChatDialog();
//                }
//            });
//            mSelectionFrame.show();
//        }
    }

    private void showEmpty() {
        mListView.setVisibility(View.GONE);
        mSideBar.setVisibility(View.GONE);
        tvTitleRight.setVisibility(View.GONE);
//        linearShare.setVisibility(View.GONE);
    }

    private void showContent() {
        mListView.setVisibility(View.VISIBLE);
        mSideBar.setVisibility(View.VISIBLE);
        tvTitleRight.setVisibility(View.VISIBLE);
//        linearShare.setVisibility(View.VISIBLE);
    }

    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };

//    private void go(String roomId, boolean isLoadAll) {
//        String str = "";
//        if (!isLoadAll) {// 只显示新联系人 需要将新联系人传过去
//            List<String> toUserIdList = new ArrayList<>();
//            for (int i = 0; i < mSortContactList.size(); i++) {
//                if (!TextUtils.isEmpty(mSortContactList.get(i).getBean().getUserId())
//                        && mSortContactList.get(i).getBean().getIsFriend() == 2){
//                    toUserIdList.add(mSortContactList.get(i).getBean().getUserId());
//                }
//            }
//            str = JSON.toJSONString(toUserIdList);
//        }
//
//        Intent intent = new Intent(NewContactsActivity.this, ContactInviteActivity.class);
//        intent.putExtra("roomId", roomId);
//        intent.putExtra("isLoadAll", isLoadAll);
//        intent.putExtra("contactStr", str);
//        startActivity(intent);
//    }

//    /*
//  创建 手机联系人 群组
//   */
//    private void showCreateGroupChatDialog() {
//        DialogHelper.showTowInputDialogAndReturnDialog(this,
//                InternationalizationHelper.getString("CREATE_ROOMS"),
//                InternationalizationHelper.getString("JX_InputRoomName"),
//                InternationalizationHelper.getString("JXAlert_InputSomething"),
//                getString(R.string.x_phone_address_group, coreManager.getSelf().getNickName()), getString(R.string.x_phone_address_group, coreManager.getSelf().getNickName()),
//                (roomNameEdit, roomDescEdit, isRead, isLook, isNeedVerify, isShowMember, isAllowSendCard) -> {
//                    String roomName = roomNameEdit.getText().toString().trim();
//                    if (TextUtils.isEmpty(roomName)) {
//                        Toast.makeText(NewContactsActivity.this, getString(R.string.room_name_empty_error), Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//
//                    String roomDesc = roomDescEdit.getText().toString();
//                    if (TextUtils.isEmpty(roomDesc)) {
//                        Toast.makeText(NewContactsActivity.this, getString(R.string.room_des_empty_error), Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//
//                    int length = 0;
//                    for (int i = 0; i < roomName.length(); i++) {
//                        String substring = roomName.substring(i, i + 1);
//                        if (CharUtils.isChinese(substring)) {  // 中文占两个字符
//                            length += 2;
//                        } else {
//                            length += 1;
//                        }
//                    }
//                    if (length > 20) {
//                        Toast.makeText(NewContactsActivity.this, getString(R.string.tip_group_name_too_long), Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//
//                    int length2 = 0;
//                    for (int i = 0; i < roomDesc.length(); i++) {
//                        String substring = roomDesc.substring(i, i + 1);
//                        if (CharUtils.isChinese(substring)) {
//                            length2 += 2;
//                        } else {
//                            length2 += 1;
//                        }
//                    }
//                    if (length2 > 100) {
//                        Toast.makeText(NewContactsActivity.this, getString(R.string.tip_group_description_too_long), Toast.LENGTH_SHORT).show();
//                        return;
//                    }
//                    createGroupChat(roomName, roomDesc, isRead, isLook, isNeedVerify, isShowMember, isAllowSendCard);
//                });
//    }

//    private void createGroupChat(final String roomName, final String roomDesc, int isRead,
//                                 int isLook, int isNeedVerify, int isShowMember, int isAllowSendCard) {
//        final String roomJid = coreManager.createMucRoom(roomName);
//        if (TextUtils.isEmpty(roomJid)) {
//            ToastUtil.showToast(mContext, getString(R.string.create_room_failed));
//            return;
//        }
//        MyApplication.mRoomKeyLastCreate = roomJid;
//        Map<String, String> params = new HashMap<>();
//        params.put("access_token", coreManager.getSelfStatus().accessToken);
//        params.put("jid", roomJid);
//        params.put("name", roomName);
//        params.put("desc", roomDesc);
//        params.put("countryId", String.valueOf(Area.getDefaultCountyId()));
//
//        params.put("showRead", isRead + "");
//        // 显示已读人数
//        PreferenceUtils.putBoolean(mContext, Constants.IS_SHOW_READ + roomJid, isRead == 1);
//        // 是否公开
//        params.put("isLook", isLook + "");
//        // 是否开启进群验证
//        params.put("isNeedVerify", isNeedVerify + "");
//        // 其他群管理
//        params.put("showMember", isShowMember + "");
//        params.put("allowSendCard", isAllowSendCard + "");
//
//        params.put("allowInviteFriend", "1");
//        params.put("allowUploadFile", "1");
//        params.put("allowConference", "1");
//        params.put("allowSpeakCourse", "1");
//
//        params.put("category", "510");// 群组类型 手机联系人群组
//
//        PreferenceUtils.putBoolean(mContext, Constants.IS_SEND_CARD + roomJid, isAllowSendCard == 1);
//
//        Area area = Area.getDefaultProvince();
//        if (area != null) {
//            params.put("provinceId", String.valueOf(area.getId()));
//        }
//        area = Area.getDefaultCity();
//        if (area != null) {
//            params.put("cityId", String.valueOf(area.getId()));
//            area = Area.getDefaultDistrict(area.getId());
//            if (area != null) {
//                params.put("areaId", String.valueOf(area.getId()));
//            }
//        }
//
//        double latitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
//        double longitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
//        if (latitude != 0)
//            params.put("latitude", String.valueOf(latitude));
//        if (longitude != 0)
//            params.put("longitude", String.valueOf(longitude));
//
//        DialogHelper.showDefaulteMessageProgressDialog(this);
//
//        HttpUtils.get().url(coreManager.getConfig().ROOM_ADD)
//                .params(params)
//                .build()
//                .execute(new BaseCallback<MucRoom>(MucRoom.class) {
//
//                    @Override
//                    public void onResponse(ObjectResult<MucRoom> result) {
//                        DialogHelper.dismissProgressDialog();
//                        if (result.getResultCode() == 1) {
//                            createRoomSuccess(result.getData().getId(), roomJid, roomName, roomDesc);
//                        } else {
//                            MyApplication.mRoomKeyLastCreate = "compatible";// 还原回去
//                            if (!TextUtils.isEmpty(result.getResultMsg())) {
//                                ToastUtil.showToast(mContext, result.getResultMsg());
//                            } else {
//                                ToastUtil.showToast(mContext, R.string.tip_server_error);
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        MyApplication.mRoomKeyLastCreate = "compatible";// 还原回去
//                        ToastUtil.showErrorNet(mContext);
//                    }
//                });
//    }

//    // 创建成功的时候将会调用此方法，将房间也存为好友
//    private void createRoomSuccess(final String roomId, String roomJid, String roomName, String
//            roomDesc) {
//        Friend friend = new Friend();
//        friend.setOwnerId(coreManager.getSelf().getUserId());
//        friend.setUserId(roomJid);
//        friend.setNickName(roomName);
//        friend.setDescription(roomDesc);
//        friend.setRoomFlag(510);
//        friend.setRoomId(roomId);
//        friend.setRoomCreateUserId(coreManager.getSelf().getUserId());
//        // timeSend作为取群聊离线消息的标志，所以要在这里设置一个初始值
//        friend.setTimeSend(TimeUtils.sk_time_current_time());
//        friend.setStatus(Friend.STATUS_FRIEND);
//        FriendDao.getInstance().createOrUpdateFriend(friend);
//        // 更新群聊界面
//        MucgroupUpdateUtil.broadcastUpdateUi(this);
//
//        go(roomId, true);
//    }

    //通过本地联系人号码，获取联系人状态
    private void getContacts() {
        phoneContacts = ContactsUtil.getPhoneContacts(this);
        if (phoneContacts != null && phoneContacts.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();

            for (Map.Entry<String, Contacts> entry : phoneContacts.entrySet()) {
                stringBuffer.append(entry.getKey() + ",");
            }
            String phones = stringBuffer.substring(0, stringBuffer.length() - 1);
            Map<String, String> params = new HashMap<>();
            params.put("access_token", coreManager.getSelfStatus().accessToken);
            params.put("telephones", phones);
            DialogHelper.showDefaulteMessageProgressDialog(this);
            HttpUtils.post().url(coreManager.getConfig().CHECK_CONTACTS)
                    .params(params)
                    .build()
                    .execute(new BaseCallback<NewContactsBean[]>(NewContactsBean[].class) {

                        @Override
                        public void onResponse(ObjectResult<NewContactsBean[]> result) {
                            DialogHelper.dismissProgressDialog();
                            if (result == null) {
                                ToastUtil.showToast(mContext, "数据获取错误");
                                return;
                            }
                            if (result.getData() != null && result.getData().length > 0) {
                                showContent();
                                tvNoContacts.setVisibility(View.GONE);
                                tvTitleRight.setVisibility(View.VISIBLE);
                                NewContactsBean[] contactsBeans = result.getData();
                                List<NewContactsBean> list = new ArrayList<>();
                                String myPhone = coreManager.getSelf().getPhone();
                                for (int i = 0; i < contactsBeans.length; i++) {
                                    LogUtil.e("123456" + contactsBeans[i].getNickName());
                                    Contacts contacts = phoneContacts.get(contactsBeans[i].getTelephone());

                                    if (contactsBeans[i].getIsFriend() != 2){
                                        contactsBeans[i].setNickName(contacts.getName());
                                    }

                                    if (!contacts.getTelephone().equals(myPhone)) {
                                        list.add(contactsBeans[i]);
                                    }
                                }

                                if (mSortContactList.size()>0){
                                    mSortContactList.clear();
                                }
                                if (mAddSortContactList.size()>0){
                                    mAddSortContactList.clear();
                                }
                                Map<String, Integer> existMap = new HashMap<>();
                                List<BaseSortModel<NewContactsBean>> sortedList = SortHelper.toSortedModelList(list, existMap, NewContactsBean::getNickName);
                                mSideBar.setExistMap(existMap);
                                for (int i = 0; i < sortedList.size(); i++) {
                                    if (sortedList.get(i).getBean().getIsFriend() != 2) {
                                        mSortContactList.add(sortedList.get(i));
                                    } else {
                                        mAddSortContactList.add(sortedList.get(i));
                                    }
                                }
                                contactsAdapter.notifyDataSetChanged();
                                if (mAddSortContactList.size() > 0) {
                                    ll_contacts_head.setVisibility(View.VISIBLE);
                                    hadAddContactsAdapter.notifyDataSetChanged();
                                } else {
                                    ll_contacts_head.setVisibility(View.GONE);
                                }

                                if (mSortContactList != null && mSortContactList.size() > 0) {
                                    mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
                                } else {
                                    tvTitleRight.setVisibility(View.GONE);
                                }
                            } else {
                                ToastUtil.showToast(mContext, result.getResultMsg());
                                tvNoContacts.setVisibility(View.VISIBLE);
                                tvTitleRight.setVisibility(View.GONE);
                                showEmpty();
                            }
                        }

                        @Override
                        public void onError(Call call, Exception e) {
                            DialogHelper.dismissProgressDialog();
                            ToastUtil.showNetError(mContext);
                        }
                    });
        } else {
            tvNoContacts.setVisibility(View.VISIBLE);
            tvTitleRight.setVisibility(View.GONE);
        }
    }

    private void isControlBatchStatus(boolean isOperating) {
        if (isOperating) {
            isInvitedMod = !isInvitedMod;
            if (isInvitedMod) {
                tvTitleRight.setText(getString(R.string.cancel));
                AnimationUtil.setVisible(tvConfirm);
                ll_contacts_head.setVisibility(View.GONE);
            } else {
                tvTitleRight.setText("批量邀请");
                AnimationUtil.setGone(tvConfirm);
                ll_contacts_head.setVisibility(View.VISIBLE);

            }
        }
        if (contactsAdapter != null) {
            contactsAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted) {
        linearNoPermission.setVisibility(View.GONE);
        linearNoPermission.postDelayed(new Runnable() {
            @Override
            public void run() {
                //解决申请权限返回白屏卡顿
                getContacts();
            }
        }, 100);

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied) {
    }

    private class ContactsAdapter extends BaseQuickAdapter<BaseSortModel<NewContactsBean>, BaseViewHolder> implements SectionIndexer {
        List<BaseSortModel<NewContactsBean>> mSortContactList;

        public ContactsAdapter(List<BaseSortModel<NewContactsBean>> data) {
            super(R.layout.item_new_contacts, data);
            this.mSortContactList = data;
        }

        @Override
        protected void convert(BaseViewHolder helper, BaseSortModel<NewContactsBean> item) {

            // 添加了头部 ，所以减1
            int position = helper.getAdapterPosition() - 1;
            TextView categoryTitleTv = helper.getView(R.id.catagory_title);
            CheckBox checkBox = helper.getView(R.id.check_box);
            TextView contactNameTv = helper.getView(R.id.contact_name_tv);
            TextView tvBtn = helper.getView(R.id.tv_contacts_button);
            LinearLayout linearBottom = helper.getView(R.id.linear_contacts_item_bottom);
            // 根据position获取分类的首字母的Char ascii值
            int section = getSectionForPosition(position);
            // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
            if (position == getPositionForSection(section)) {
                categoryTitleTv.setVisibility(View.VISIBLE);
                categoryTitleTv.setText(mSortContactList.get(position).getFirstLetter());
            } else {
                categoryTitleTv.setVisibility(View.GONE);
            }
            final NewContactsBean contact = mSortContactList.get(position).getBean();
            if (mSortContactList.size() > 0
                    && position == mSortContactList.size() - 1 && isInvitedMod) {
                linearBottom.setVisibility(View.VISIBLE);
            } else {
                linearBottom.setVisibility(View.GONE);
            }
            if (contact != null) {
                contactNameTv.setText(contact.getNickName());
                itemChange(contact, tvBtn, checkBox);
            }
        }

        //根据 数据格式/是否批量邀请 -> 改变item布局
        private void itemChange(final NewContactsBean contact, TextView tvBtn, CheckBox checkBox) {
            //未注册
            if (isInvitedMod) {//批量邀请
                checkBox.setVisibility(View.VISIBLE);
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        contact.setChecked(isChecked);
                    }
                });
                checkBox.setChecked(contact.isChecked());
                tvBtn.setVisibility(View.GONE);
            } else {//普通邀请
                checkBox.setVisibility(View.GONE);
                tvBtn.setVisibility(View.VISIBLE);
                tvBtn.setText("邀请");
                tvBtn.setTextColor(Color.WHITE);
                tvBtn.setBackgroundResource(R.drawable.bg_round_green);
                tvBtn.setPadding(24, 10, 24, 10);
                initBtnEvent(tvBtn, true, contact);
            }
        }

        //按钮点击事件
        private void initBtnEvent(TextView tvBtn, boolean isInvite, NewContactsBean contact) {
            tvBtn.setEnabled(true);
            if (isInvite) {
                tvBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sendSms(contact.getTelephone());
                    }
                });
            } else {
                tvBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        loadOthersInfoFromNet(contact.getUserId());
                    }
                });
            }
        }

        @Override
        public Object[] getSections() {
            return null;
        }

        @Override
        public int getPositionForSection(int section) {
            for (int i = 0; i < mSortContactList.size(); i++) {
                String sortStr = mSortContactList.get(i).getFirstLetter();
                char firstChar = sortStr.toUpperCase().charAt(0);
                if (firstChar == section) {
                    return i;
                }
            }
            return -1;
        }

        @Override
        public int getSectionForPosition(int position) {
            return mSortContactList.get(position).getFirstLetter().charAt(0);
        }

        public String getFirstStr(int position) {
            if (mSortContactList != null && mSortContactList.size() > 0) {
                return mSortContactList.get(position).getFirstLetter();
            }
            return "";
        }
    }

    //发送短信
    private void sendSms(String number) {
        Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + number));
        sendIntent.putExtra("sms_body", getString(R.string.sms_content, coreManager.getSelf().getAccount())
                + coreManager.getConfig().website);
        startActivity(sendIntent);
    }

    // 在联系人内加好友
    private void addFriendInContacts(String toUserIds, User mUser) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", toUserIds);
        params.put("fromAddType", PersonalCenterActivity.FROM_ADD_TYPE_OTHER);
        DialogHelper.showDefaulteMessageProgressDialog(this);
        // 首先是调接口，
        HttpUtils.get().url(coreManager.getConfig().FRIENDS_ATTENTION_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<AddAttentionResult>(AddAttentionResult.class) {

                    @Override
                    public void onResponse(ObjectResult<AddAttentionResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1 && result.getData() != null) {
                            getContacts();
                            if (result.getData().getType() == 1 || result.getData().getType() == 3) {
                                // 需要验证就发送打招呼的消息，
                                doSayHello(InternationalizationHelper.getString("JXUserInfoVC_Hello"), mUser);
                            } else if (result.getData().getType() == 2 || result.getData().getType() == 4) {// 已经是好友了
                                NewFriendMessage message = NewFriendMessage.createWillSendMessage(
                                        coreManager.getSelf(), XmppMessage.TYPE_FRIEND, null, mUser);
                                NewFriendDao.getInstance().createOrUpdateNewFriend(message);
                                // 不需要验证的话直接加上，就发个xmpp消息，
                                // 这里最终调用smack的方法发送xmpp消息，
                                coreManager.sendNewFriendMessage(mUser.getUserId(), message);
                                updateMyself(message, mUser);
                            } else if (result.getData().getType() == 5) {
                                ToastUtil.showToast(mContext, R.string.add_attention_failed);
                            }
                        } else {
                            Toast.makeText(mContext, result.getResultMsg() + "", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        Toast.makeText(mContext, R.string.tip_hello_failed, Toast.LENGTH_SHORT).show();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    // 加载好友的信息
    private void loadOthersInfoFromNet(String toUserId) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("userId", toUserId);
        HttpUtils.get().url(coreManager.getConfig().USER_GET_URL)
                .params(params)
                .build()
                .execute(new BaseCallback<User>(User.class) {

                    @Override
                    public void onResponse(ObjectResult<User> result) {
                        if (Result.checkSuccess(mContext, result)) {
                            User mUser = result.getData();
                            if (mUser.getUserType() != 2) {// 公众号不做该操作 否则会将公众号的status变为好友
                                addFriendInContacts(toUserId, mUser);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

    // 需要验证时，打招呼
    private void doSayHello(String text, User toUser) {
        if (TextUtils.isEmpty(text)) {
            text = InternationalizationHelper.getString("HEY-HELLO");
        }
        NewFriendMessage message = NewFriendMessage.createWillSendMessage(coreManager.getSelf(),
                XmppMessage.TYPE_SAYHELLO, text, toUser);
        NewFriendDao.getInstance().createOrUpdateNewFriend(message);
        // 这里最终调用smack的发送消息，
        coreManager.sendNewFriendMessage(toUser.getUserId(), message);
        // 发送打招呼的消息
        ChatMessage sayMessage = new ChatMessage();
        sayMessage.setFromUserId(coreManager.getSelf().getUserId());
        sayMessage.setFromUserName(coreManager.getSelf().getNickName());
        sayMessage.setContent(InternationalizationHelper.getString("HEY-HELLO"));
        sayMessage.setType(XmppMessage.TYPE_TEXT); //文本类型
        sayMessage.setMySend(true);
        sayMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_SUCCESS);
        sayMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
        sayMessage.setTimeSend(TimeUtils.sk_time_current_time());
        ChatMessageDao.getInstance().saveNewSingleChatMessage(message.getOwnerId(), message.getUserId(), sayMessage);
        remindMySelf(message, toUser);
    }

    //打招呼后通知自己
    private void remindMySelf(NewFriendMessage message, User toUser) {
        ChatMessage sayChatMessage = new ChatMessage();
        sayChatMessage.setContent(InternationalizationHelper.getString("JXFriendObject_WaitPass"));
        sayChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
        // 各种Dao都是本地数据库的操作，
        // 这个是好友表里更新最后一条消息，
        FriendDao.getInstance().updateLastChatMessage(coreManager.getSelf().getUserId(), Friend.ID_NEW_FRIEND_MESSAGE, sayChatMessage);

        // 这个是新的好友界面用的，等验证什么的都在新的好友页面，
        NewFriendDao.getInstance().changeNewFriendState(toUser.getUserId(), Friend.STATUS_10);// 好友状态
        ListenerManager.getInstance().notifyNewFriend(coreManager.getSelf().getUserId(), message, true);
    }

    //不需验证时，添加好友成功更新自己UI
    private void updateMyself(NewFriendMessage message, User toUser) {
        NewFriendDao.getInstance().ascensionNewFriend(message, Friend.STATUS_FRIEND);
        FriendHelper.addFriendExtraOperation(coreManager.getSelf().getUserId(), toUser.getUserId());// 加好友

        ChatMessage addChatMessage = new ChatMessage();
        addChatMessage.setContent(InternationalizationHelper.getString("JXNearVC_AddFriends") + ":" + toUser.getNickName());
        addChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
        FriendDao.getInstance().updateLastChatMessage(coreManager.getSelf().getUserId(), Friend.ID_NEW_FRIEND_MESSAGE, addChatMessage);

        NewFriendDao.getInstance().changeNewFriendState(toUser.getUserId(), Friend.STATUS_22);//添加了xxx
        FriendDao.getInstance().updateFriendContent(coreManager.getSelf().getUserId(), toUser.getUserId(), InternationalizationHelper.getString("JXMessageObject_BeFriendAndChat"), XmppMessage.TYPE_TEXT, TimeUtils.sk_time_current_time());
        ListenerManager.getInstance().notifyNewFriend(coreManager.getSelf().getUserId(), message, true);
        CardcastUiUpdateUtil.broadcastUpdateUi(mContext);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_CONTACTS_CODE) {
            boolean isReadContacts = PermissionUtil.checkSelfPermissions(NewContactsActivity.this, new String[]{Manifest.permission.READ_CONTACTS});
            if (isReadContacts) {
                linearNoPermission.setVisibility(View.GONE);
                getContacts();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
